<?php
// +----------------------------------------------------------------------
//            -------------------------
//           /   / ----------------\  \
//          /   /             \  \
//         /   /              /  /
//        /   /    /-------------- /  /
//       /   /    /-------------------\  \
//      /   /                   \  \
//     /   /                     \  \
//    /   /                      /  /
//   /   /      /----------------------- /  /
//  /-----/      /---------------------------/
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://baimifan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: Sage 2016/4/22  16:46
// +----------------------------------------------------------------------
namespace Admin\Controller;
use Service\ServiceContainer;
class RefundController extends CashierBaseController {

    function __construct() {
        parent::__construct();
        $this->di=new ServiceContainer();
    }

    function index() {
        $this->display();
    }

    function doRefund() {
        $data = I("post.");
        switch ($data['type']) {
            case 1:
                //购书
                $Orderbook=M('Order_book');
                $Orderbook->startTrans();
                $d=$Orderbook->where(['order_id'=>$data['order_id'],'is_refund'=>'0'])->find();
                if(!$d){
                    $Orderbook->rollback();
                    $j=[
                        'status'=>'error',
                        'data'=>'订单不存在'
                    ];
                    break;
                }
                $dp=M('Pay')->where(['pay_id'=>$d['pay_id']])->find();
                //生成退货款订单
                $map_refund=[
                    'user_id'=>$d['user_id'],
                    'status'=>1,
                    'type'=>1,
                    'way'=>'cash',
                    'summary'=>'购书退款,订单号:'.$data['order_id'].',支付流水号:'.$dp['pay_id'],
                    'money'=>$dp['money_real']-$dp['money_zero'],
                    'money_real'=>$data['money_real']
                ];
                //微信退款使用原金额
                if($dp['way']=='wechat' && $dp['money_real']!='0'){
                    $map_refund['money_real']=$dp['money_real'];
                }
                $refund_id=M('Refund')->data($map_refund)->add();
                if(!$refund_id){
                    $Orderbook->rollback();
                    $j=[
                        'status'=>'error',
                        'data'=>'系统错误,退货款订单生成错误'
                    ];
                    break;
                }
                //更改订单退货款状态
                $ro=$Orderbook->where(['order_id'=>$data['order_id']])->data(['is_refund'=>1,'refund_id'=>$refund_id])->save();
                if(!$ro){
                    $Orderbook->rollback();
                    $j=[
                        'status'=>'error',
                        'data'=>'系统错误,更改退货款状态错误'
                    ];
                    break;
                }
                //图书退货款后返回库存
                $db=M('Order_has_book')->where(['order_id'=>$data['order_id']])->select();
                foreach($db as $k=>$v){
                    $r=M('Book')->where(['book_id'=>$v['book_id']])->setInc('stock_buy',$v['quantity']);
                    if(!$r){
                        $Orderbook->rollback();
                        $j=[
                            'status'=>'error',
                            'data'=>'系统错误,更新库存错误'
                        ];
                        break;
                    }
                }
                //微信退款条件检查
                if($dp['way']=='wechat' && $dp['money_real']!='0'){
                    //微信退款
                    $r=$this->di->get('WechatService')->wx_refund($dp['money_real'],$d['pay_id']);
                    if($r['status']=='error'){
                        $Orderbook->rollback();
                        $j=[
                            'status'=>'error',
                            'data'=>'系统错误,微信退款错误'.$r['data']['return_msg']
                        ];
                        break;
                    }
                }

                $Orderbook->commit();
                $j=[
                    'status'=>'success',
                    'data'=>'退款成功'
                ];
                break;
            case 2:
                //充值
                $Deposit=M('View_deposit');
                $dd=$Deposit->where(['deposit_id'=>$data['order_id'],'is_refund'=>'0'])->find();
                $Deposit->startTrans();
                if(!$dd){
                    $Deposit->rollback();
                    $j=[
                        'status'=>'error',
                        'data'=>'此订单不存在'
                    ];
                    break;
                }
                $dp=M('Pay')->where(['pay_id'=>$dd['pay_id']])->find();
                //生成退货款订单
                $map_refund=[
                    'user_id'=>$dp['user_id'],
                    'status'=>1,
                    'type'=>2,
                    'way'=>'cash',
                    'summary'=>'充值退款,订单号:'.$data['order_id'].',支付流水号:'.$dp['pay_id'],
                    'money'=>$dp['money_real']-$dp['money_zero'],
                    'money_real'=>$data['money_real']
                ];
                //微信退款使用原金额
                if($dp['way']=='wechat' && $dp['money_real']!='0'){
                    $map_refund['money_real']=$dp['money_real'];
                }

                $refund_id=M('Refund')->data($map_refund)->add();
                if(!$refund_id){
                    $Deposit->rollback();
                    $j=[
                        'status'=>'error',
                        'data'=>'系统错误,退货款订单生成错误'
                    ];
                    break;
                }
                //更改订单退货款状态
                $rd=$Deposit->where(['deposit'=>$data['order_id']])->data(['is_refund'=>1,'refund_id'=>$refund_id])->save();
                if(!$rd){
                    $Deposit->rollback();
                    $j=[
                        'status'=>'error',
                        'data'=>'系统错误,更改退货款状态错误'
                    ];
                    break;
                }
                //更改会员有效期限
                $dc=M('Card')->where(['card_id'=>$dd['card_id']])->find();
                if(!$dc){
                    $Deposit->rollback();
                    $j=[
                        'status'=>'error',
                        'data'=>'系统错误,会员卡错误'
                    ];
                    break;
                }
                $map_card=[];
                if(strtotime($dc['create_time']) > strtotime('-'.$dd['month'].' months',strtotime($dc['expire_time']))){
                    //有效期不够扣
                    $map_card['expire_time']=$map_card['create_time'];
                    $map_card['discount_apply']=1;
                    $map_card['discount_buy']=1;
                }else{
                    $map_card['expire_time']=date('Y-m-d H:i:s',strtotime('-'.$dd['month'].' months',strtotime($dc['expire_time'])));
                }
                //次数不够扣直接扣为0
                if($dc['num_delivery']<$dd['num_delivery']){
                    $map_card['num_delivery']=0;
                }else{
                    $map_card['num_delivery']=$dc['num_delivery']-$dd['num_delivery'];
                }
                //次数不够扣直接扣为0
                if($dc['num_activity']<$dd['num_activity']){
                    $map_card['num_activity']=0;
                }else{
                    $map_card['num_activity']=$dc['num_activity']-$dd['num_activity'];
                }
                $map_card['remark']=$dc['remark'].'退款操作,退卡类型:'.$dd['name'].',退会员有效期:'.$dd['month'].'个月;<br>';

                $r=M('Card')->where(['card_id'=>$dd['card_id']])->data($map_card)->save();
                if(!$r){
                    $Deposit->rollback();
                    $j=[
                        'status'=>'error',
                        'data'=>'系统错误,更新会员卡错误'
                    ];
                    break;
                }

                //微信退款条件检查
                if($dp['way']=='wechat' && $dp['money_real']!='0'){
                    //微信退款
                    $r=$this->di->get('WechatService')->wx_refund($dp['money_real'],$dd['pay_id']);
                    if($r['status']=='error'){
                        $Deposit->rollback();
                        $j=[
                            'status'=>'error',
                            'data'=>'系统错误,微信退款错误'.$r['data']['return_msg']
                        ];
                        break;
                    }
                }
                $Deposit->commit();
                $j=[
                    'status'=>'success',
                    'data'=>'退款成功'
                ];
                break;
            case 3:
                //活动报名
                $Acta=M('View_activity_apply');
                $Acta->startTrans();
                $da=$Acta->where(['apply_id'=>$data['order_id'],'is_refund'=>'0'])->find();
                if(!$da){
                    $Acta->rollback();
                    $j=[
                        'status'=>'error',
                        'data'=>'订单不存在'
                    ];
                    break;
                }
//                $end_time=date('Y-m-d H:i:s',strtotime(date('Y-m-d',strtotime($da['activity_start']))));
                $end_time=date('Y-m-d H:i:s',strtotime(date('Y-m-d',strtotime($da['apply_end']))));

                if(time() > strtotime($end_time)-24*3600){
                    $Acta->rollback();
                    $j=[
                        'status'=>'error',
//                        'data'=>'无法退货款，只可在报名前一天退款'
                        'data'=>'无法退货款，只可在报名结束前24小时之前退款！'
                    ];
                    break;
                }
                $dp=M('Pay')->where(['pay_id'=>$da['pay_id']])->find();
                //生成退货款订单
                $map_refund=[
                    'user_id'=>$dp['user_id'],
                    'status'=>1,
                    'type'=>3,
                    'way'=>'cash',
                    'summary'=>'活动退款,订单号:'.$data['order_id'].',支付流水号:'.$dp['pay_id'],
                    'money'=>$dp['money_real']-$dp['money_zero'],
                    'money_real'=>$data['money_real']
                ];
                $refund_id=M('Refund')->data($map_refund)->add();
                if(!$refund_id){
                    $Acta->rollback();
                    $j=[
                        'status'=>'error',
                        'data'=>'系统错误,退货款订单生成错误'
                    ];
                    break;
                }
                //更改原订单退货款状态
                $ra=$Acta->where(['apply_id'=>$data['order_id']])->data(['is_refund'=>1,'refund_id'=>$refund_id])->save();
                if(!$ra){
                    $Acta->rollback();
                    $j=[
                        'status'=>'error',
                        'data'=>'系统错误,更改退货款状态错误'
                    ];
                    break;
                }
                //更改活动信息
                $ra=M('Activity')->where(['activity_id'=>$da['activity_id']])->setInc('apply_num',1);
                if(!$ra){
                    $Acta->rollback();
                    $j=[
                        'status'=>'error',
                        'data'=>'系统错误,更改活动数据错误'
                    ];
                    break;
                }
                //更改会员卡可免次数
                if($da['is_applyfree']>0){
                    $rc=M('Card')->where(['user_id'=>$da['user_id']])->setInc('num_activity',$da['num_deduct']);
                    if(!$rc){
                        $Acta->rollback();
                        $j=[
                            'status'=>'error',
                            'data'=>'系统错误,更改会员数据错误'
                        ];
                        break;
                    }
                }
                $Acta->commit();
                $j=[
                    'status'=>'success',
                    'data'=>'退款成功'
                ];
                break;
            default:
                $j = [
                    'status'=>'error',
                    'data'=>'无此类型'
                ];
                break;
        }
        echo json_encode($j,JSON_UNESCAPED_UNICODE);
    }

    function getOrder() {
        $type = I("post.type");
        $order_id = I("post.order_id");
        switch ($type) {
            case 1:
                //购书
                $d = M('Order_book')->alias('a')
                    ->where(['a.order_id' => $order_id , 'a.type' => '0' , 'a.state_order' => '1' , 'a.is_refund' => '0'])
                    ->join('pay b on a.pay_id=b.pay_id' , 'left')
                    ->join('card d on a.user_id=d.user_id','left')
                    ->find();
//                dump($d);
                if ($d) {
                    $data['order_id'] = $d['order_id'];
                    $data['pay_id'] = $d['pay_id'];
                    $data['create_time'] = $d['create_time'];
                    $data['content'] = '购书';
                    $data['money'] = $d['money_real'] - $d['money_zero']; //实收
                    $data['card_id'] = $d['card_id'];
                    $j = ['status' => 'success' , 'data' => $data];
                } else {
                    $j = ['status' => 'error' , 'data' => "无此购书订单或订单已退款(只支持已支付未发货的图书退款)"];
                }
                break;
            case 2:
                //充值
                $d = M('Deposit')->alias('a')
                    ->where(['a.deposit_id' => $order_id , 'a.is_refund' => '0'])
                    ->join('pay b on a.pay_id=b.pay_id' , 'left')
                    ->join('deposit_type c on a.type_id=c.type_id' , 'left')
                    ->join('card d on a.card_id=d.card_id','left')
                    ->find();
                if ($d) {
                    $data['order_id'] = $d['deposit_id'];
                    $data['pay_id'] = $d['pay_id'];
                    $data['create_time'] = $d['create_time'];
                    $data['content'] = '充值:' . $d['name'] . ",￥" . $d['price'];
                    $data['money'] = $d['money_real'] - $d['money_zero']; //实收
                    $data['card_id'] = $d['card_id'];
                    $j = ['status' => 'success' , 'data' => $data];
                } else {
                    $j = ['status' => 'error' , 'data' => "无此充值订单或订单已退款"];
                }
                break;
            case 3:
                //活动
                $d = M('Activity_apply')->alias('a')
                    ->where(['a.apply_id' => $order_id , 'a.is_refund' => '0'])
                    ->join('pay b on a.pay_id=b.pay_id' , 'left')
                    ->join('activity c on a.activity_id=c.activity_id' , 'left')
                    ->join('card d on a.user_id=d.user_id','left')->find();
                if ($d) {
                    $data['order_id'] = $d['apply_id'];
                    $data['pay_id'] = $d['pay_id'];
                    $data['create_time'] = $d['create_time'];
                    $data['content'] = '活动:' . $d['title'];
                    $data['money'] = $d['money_real'] - $d['money_zero']; //实收
                    $data['card_id'] = $d['card_id'];
                    $j = ['status' => 'success' , 'data' => $data];
                } else {
                    $j = ['status' => 'error' , 'data' => "无此活动订单或订单已退款"];
                }
                break;
            default:
                $j = ['status' => 'error' , 'data' => '类型不存在'];
                break;
        }
        echo json_encode($j , JSON_UNESCAPED_UNICODE);
        return;
    }
}